package com.upc.feedish;

import androidx.appcompat.app.AppCompatActivity;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import android.content.Intent;
import android.content.SharedPreferences;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class AddDeviceActivity extends AppCompatActivity {

    private TextView nfcTView;
    private EditText nfcContent;
    private EditText deviceNameET;
    private NfcAdapter nfcAdapter;
    private Handler handler;

    private Toast getSuccessToast;
    private Toast addSuccessToast;
    private Toast failure_Toast;
    private Toast timeOut_Toast;

    private String readResult;
    private String deviceName;
    private String deviceId;
    private String username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1:
                        addSuccessToast.show();
                        AddDeviceActivity.this.finish();
                }

            };
        };
        setContentView(R.layout.activity_add_device);

        SharedPreferences sp = getSharedPreferences("data",MODE_PRIVATE);
        username= sp.getString("username","");

        getSuccessToast = Toast.makeText(this, "已自动填入设备ID",Toast.LENGTH_SHORT);
        addSuccessToast = Toast.makeText(this, "设备添加成功",Toast.LENGTH_SHORT);
        failure_Toast = Toast.makeText(this,"失败",Toast.LENGTH_SHORT);
        timeOut_Toast = Toast.makeText(this,"网络连接超时",Toast.LENGTH_SHORT);
        nfcTView = (TextView) findViewById(R.id.info_tv);
        nfcContent = (EditText) findViewById(R.id.nfcContent);
        deviceNameET = findViewById(R.id.deviceName);

        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter == null) {
            nfcTView.setText("设备不支持NFC！");
            //finish();
            return;
        }
        if (nfcAdapter != null && !nfcAdapter.isEnabled()) {
            nfcTView.setText("请在系统设置中先启用NFC功能！");
            //finish();
            return;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
            readNfcTag(getIntent());
        }
        //nfcContent.setText(readResult);
    }


    private boolean readNfcTag(Intent intent) {
        Parcelable[] rawArray = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        NdefMessage mNdefMsg = (NdefMessage) rawArray[0];
        NdefRecord mNdefRecord = mNdefMsg.getRecords()[0];

        try {
            if (mNdefRecord != null) {
                readResult = new String(mNdefRecord.getPayload(), "UTF-8");
                readResult = readResult.substring(3);
                nfcContent.setText(readResult);
                getSuccessToast.show();
                return true;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        };

        return false;
    }

    public void confirm(View view) {
        if(nfcContent.getText().toString().equals(null)||deviceNameET.getText().toString().equals(null)){
            Toast.makeText(AddDeviceActivity.this,"请将信息填写完整",Toast.LENGTH_SHORT).show();
        }
        else{
            deviceName = deviceNameET.getText().toString();
            deviceId = nfcContent.getText().toString();
            AddDeviceThread addDeviceThread = new AddDeviceThread();
            addDeviceThread.start();
        }
    }

    public class AddDeviceThread extends Thread{
        public void run(){
            try {
                String json = "{\"username\":\""+username+"\",\"deviceId\":\""+deviceId+"\",\"name\":\""+deviceName+"\"}";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://1.116.33.97:8080/addDevice")
                        .post(RequestBody.create(MediaType.parse("application/json"),json))
                        .build();
                Response response = client.newCall(request).execute();
                String responseData = response.body().string();
                JSONObject jsonObject=new JSONObject(responseData);
                int code=(int)jsonObject.get("code");
                if(code == 100){
                    //Success.show();
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
                else{
                    failure_Toast.show();
                }
            }catch (Exception e){
                e.printStackTrace();
                timeOut_Toast.show();
            }
        }
    }

//    private void readFromTag(Intent intent) {
//        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
//            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
//                    NfcAdapter.EXTRA_NDEF_MESSAGES);
//            NdefMessage msgs[] = null;
//            int contentSize = 0;
//            if (rawMsgs != null) {
//                msgs = new NdefMessage[rawMsgs.length];
//                for (int i = 0; i < rawMsgs.length; i++) {
//                    msgs[i] = (NdefMessage) rawMsgs[i];
//                    contentSize += msgs[i].toByteArray().length;
//                }
//            }
//            try {
//                if (msgs != null) {
//                    NdefRecord record = msgs[0].getRecords()[0];
//                    readResult = new String(record.getPayload(), "UTF-8");
//                    nfcContent.setText(readResult);
//                    //String textRecord = parseTextRecord(record);
//                    //mTagText += textRecord + "\n\ntext\n" + contentSize + " bytes";
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }
//
//    public static String parseTextRecord(NdefRecord ndefRecord) {
//        /**
//         * 判断数据是否为NDEF格式
//         */
//        //判断TNF
//        if (ndefRecord.getTnf() != NdefRecord.TNF_WELL_KNOWN) {
//            return null;
//        }
//        //判断可变的长度的类型
//        if (!Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
//            return null;
//        }
//        try {
//            //获得字节数组，然后进行分析
//            byte[] payload = ndefRecord.getPayload();
//            //下面开始NDEF文本数据第一个字节，状态字节
//            //判断文本是基于UTF-8还是UTF-16的，取第一个字节"位与"上16进制的80，16进制的80也就是最高位是1，
//            //其他位都是0，所以进行"位与"运算后就会保留最高位
//            String textEncoding = ((payload[0] & 0x80) == 0) ? "UTF-8" : "UTF-16";
//            //3f最高两位是0，第六位是1，所以进行"位与"运算后获得第六位
//            int languageCodeLength = payload[0] & 0x3f;
//            //下面开始NDEF文本数据第二个字节，语言编码
//            //获得语言编码
//            String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
//            //下面开始NDEF文本数据后面的字节，解析出文本
//            String textRecord = new String(payload, languageCodeLength + 1,
//                    payload.length - languageCodeLength - 1, textEncoding);
//            return textRecord;
//        } catch (Exception e) {
//            throw new IllegalArgumentException();
//        }
//    }




}